/* Funciones para suscribirse */
function subscribe(subject_id) {
  start_loading();
  
  $.get(site_url('subjects/subscribe/' + subject_id), {}, function(data){
    if(data == '!ok!') {
      stop_loading_msg('Te has suscrito a este curso');
      setTimeout(function(){start_loading(); location.href = location.href;}, 3000); /* Recargamos la pagina */
    }
    else if(data == '!login!') {
      location.href = site_url('auth/login?referer=' + escape(location.href));
    }
    else {
      stop_loading_msg('Ha ocurrido un error');
    }
  });
}

function subscribe_password(subject_id) {
  location.href = '#subscribe-anchor';
  $('#subscribe-password').slideDown();
  $('#subject_password').focus();
}

function submit_password(subject_id) {
  start_loading();
  
  $.post(site_url('subjects/subscribe/' + subject_id), {password: $('#subject_password').val()}, function(data){
    if(data == '!ok!') {
      stop_loading_msg('Te has suscrito a este curso');
      $('#subscribe-password').slideUp(); 
      setTimeout(function(){start_loading(); location.reload();}, 3000); /* Recargamos la pagina */
    }
    else {
      stop_loading_msg('La contrase&ntilde;a es incorrecta!');
    }
  });
}

function unsubscribe(subject_id) {
  
  if(confirm('Estás seguro de querer eliminar esta suscripción?')) {
    start_loading();

    $.get(site_url('subjects/unsubscribe/' + subject_id), {}, function(){
      stop_loading_msg('Ya no est&aacute;s suscrito a este curso');
      setTimeout(function(){start_loading(); location.reload();}, 3000); /* Recargamos la pagina */
    });
  }
}

$('document').ready(function(){
  
  
  /* Si el usuario cambia sus notificaciones, mandamos por ajax */
  $('#receive-news-notifications').click(function(){
    var checkbox = $('#receive-news-notifications');
    
    start_loading();
    
    /* Deshabilitamos por mientras */
    checkbox.attr('disabled', 'true');
    
    /* El id del ramo */
    var id_subject = checkbox.attr('name').split('-')[1];
    
    $.get(site_url('subjects/options/' + id_subject + '/news/' + (checkbox.attr('checked') ? 'on' : 'off')), {}, function(){
      stop_loading_msg('Cambios guardados');
      checkbox.attr('disabled', '');
    });
    
    // stop_loading();
  });
  
  /* Ahora para los archivos */
  $('#receive-files-notifications').click(function(){
    var checkbox = $('#receive-files-notifications');
    
    start_loading();
    
    /* Deshabilitamos por mientras */
    checkbox.attr('disabled', 'true');
    
    /* El id del ramo */
    var id_subject = checkbox.attr('name').split('-')[1];
    
    $.get(site_url('subjects/options/' + id_subject + '/files/' + (checkbox.attr('checked') ? 'on' : 'off')), {}, function(){
      stop_loading_msg('Cambios guardados');
      checkbox.attr('disabled', '');
    });
    
    // stop_loading();
  });
  
});